//
//  WBNetworkManager.swift
//  weibo
//
//  Created by wenquan wang on 12/2/16.
//  Copyright © 2016 wenquan wang. All rights reserved.
//

import UIKit
import AFNetworking

enum WBHTTPMethod {
    case GET
    case POST
}
class WBNetworkManager: AFHTTPSessionManager {
    
    //singleton
    static let shared: WBNetworkManager = {
        let instance = WBNetworkManager()
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    lazy var userAccount = WBUserAccount()

    var userLogin: Bool {
        return userAccount.access_token != nil
    }
    
    func tokenRequest(method: WBHTTPMethod = .GET, urlString: String, parameters:[String: AnyObject]?,
                      completion: @escaping ((json: AnyObject?, isSuccess: Bool))->()){
        
        var params = parameters
        if parameters == nil {
            params = [String: AnyObject]()
        }
        guard let token = userAccount.access_token else {
            
            // send notification
            print("Error no token info!")
            NotificationCenter.default.post(
                name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                object: nil)
            
            completion((json: nil, isSuccess: false))
            return
        }
        
        params!["access_token"] = token as AnyObject?
        
        request(method: method, urlString: urlString, parameters: params!, completion: completion)
        
    }
    
    func request(method: WBHTTPMethod = .GET, urlString: String, parameters:[String: AnyObject],
                 completion: @escaping ((json: AnyObject?, isSuccess: Bool))->()) {
        let success = { (task: URLSessionDataTask, json: Any?) ->() in
            completion((json:json as AnyObject?, isSuccess:true))
        }
        let failure = { (task: URLSessionDataTask?, error: Any?) ->() in
            
            print("network request error! \(error)")
            
            if(task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("Token is expired!!")
                
                // send notification
                NotificationCenter.default.post(
                    name: NSNotification.Name(rawValue: WBUserShouldLoginNotification),
                    object: "bad token")
            }
            
            completion((json:nil, isSuccess:false))
        }
        if method == .GET{
           get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        else{
            post(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}
